package com.xoa.service.attend;

import com.xoa.dao.attend.AttendanceOvertimeMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.attend.AttendEvection;
import com.xoa.model.attend.AttendanceOvertime;
import com.xoa.model.attend.AttendanceOvertimeFlowRunPrcs;
import com.xoa.model.common.SysCode;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFast;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.work.WorkService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateCompute;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/11/22.
 */
@Service
public class AttendanceOvertimeService {
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;

    @Autowired
    private AttendanceOvertimeMapper attendanceOvertimeMapper;
    /**
     * 创建人：季佳伟
     * 创建时间：2017-11-21  下午5:40:17
     * 方法介绍：查询登录人一段时间内的加班状况
     * 参数说明：
     */
    public ToJson<AttendanceOvertime> queryAttendanceOvertimeByUserId(String beginDate, String endDate,HttpServletRequest req){
        ToJson<AttendanceOvertime> json = new ToJson<AttendanceOvertime>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(),redisSessionId).getUserId();
            List<Date> dates = DateCompute.getBetweenDates(DateFormat.DateToStr(beginDate), DateFormat.DateToStr(endDate));
            List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeMapper.queryAttendanceOvertimeByUserId(userId);
            List<AttendanceOvertime> newAttendanceOvertimeList = new ArrayList<AttendanceOvertime>();
            if (attendanceOvertimeList.size() > 0){
                for (AttendanceOvertime attendanceOvertime : attendanceOvertimeList){
                    for (Date nowDate : dates){
                        String aTime = DateFormat.getDatestrTime(attendanceOvertime.getRecordTime()).substring(0,10);
                        String nTime = DateFormat.getDatestr(nowDate);
                        if (aTime.equals(nTime)){
                            newAttendanceOvertimeList.add(attendanceOvertime);
                        }

                    }
                }
                json.setObj(newAttendanceOvertimeList);
                json.setFlag(0);
                json.setMsg("err");

            }else {
                json.setMsg("err");
                json.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    public BaseWrapper addAttendanceOvertime(String createDate, HttpServletRequest request){
        BaseWrapper baseWrapper=new BaseWrapper();
        AttendanceOvertime attendanceOvertime=new AttendanceOvertime();
        AttendEvection attendEvection=new AttendEvection();
        String  sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        List<SysCode>  SysCode= sysCodeMapper.getSysCode("KQQJTYPE");
        for(SysCode sysCode:SysCode){
            if(sysCode.getCodeName().equals("加班申请")){
                ToJson<FlowFast> flowFastToJson=  wfeFlowRunInfo.workFastAdd(users, Integer.parseInt(sysCode.getCodeNo()) ,1,"1","",request,sqlType,"",null);
                if(flowFastToJson.isFlag()){
                    FlowFast flowFast=(FlowFast)flowFastToJson.getObject();
                    attendanceOvertime.setUserId(users.getUserId());
                    attendanceOvertime.setRegisterIp(IpAddr.getIpAddress(request));
                    attendanceOvertime.setRecordTime(DateFormat.getDate(createDate));
                    attendanceOvertime.setRunId(flowFast.getFlowRun().getRunId());
                    attendanceOvertime.setStatus("1");
                    attendanceOvertime.setTableName("attendance_overtime");
                    attendanceOvertime.setAllow("0");
                  int amount=attendanceOvertimeMapper.insertSelective(attendanceOvertime);
                    if(amount>0){
                        attendanceOvertime.setFlowId(flowFast.getFlowTypeModel().getFlowId().toString());
                        attendanceOvertime.setFlowName(flowFast.getFlowTypeModel().getFlowName());
                        baseWrapper.setFlag(true);
                        baseWrapper.setStatus(true);
                        baseWrapper.setData(attendanceOvertime);
                        baseWrapper.setMsg("更新成功");
                    }
                }
            }

        }
        return  baseWrapper;

    }


    public ToJson<AttendanceOvertimeFlowRunPrcs> queryAllAttendanceOvertime(Integer page, Integer pageSize, Boolean useFlag, HttpServletRequest request, String FlowAllow) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("userId", users.getUserId());
        objectMap.put("flowAllow",FlowAllow);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ToJson<AttendanceOvertimeFlowRunPrcs> json = new ToJson<AttendanceOvertimeFlowRunPrcs>(1, "error");
        try{
            List<AttendanceOvertimeFlowRunPrcs> attendOvertimeList=attendanceOvertimeMapper.queryAllAttendanceOvertime(objectMap);
            for (AttendanceOvertime attendanceOvertime:attendOvertimeList){
                String date= DateFormat.getDatestr(attendanceOvertime.getRecordTime()).substring(0,10);
                if(!StringUtils.checkNull(attendanceOvertime.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendanceOvertime.getUserId())!=null){
                        attendanceOvertime.setUserName(usersMapper.findUsersByuserId(attendanceOvertime.getUserId()).getUserName());
                    }
                    if(usersMapper.findUsersByuserId(attendanceOvertime.getUserId())!=null){
                        attendanceOvertime.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendanceOvertime.getUserId()).getDeptId()));
                    }
                }

                if(!StringUtils.checkNull(attendanceOvertime.getAgent())){
                    if(usersMapper.findUsersByuserId(attendanceOvertime.getAgent())!=null){
                        attendanceOvertime.setAgent(usersMapper.findUsersByuserId(attendanceOvertime.getAgent()).getUserName());
                    }
                }
                if(!StringUtils.checkNull(attendanceOvertime.getStatus())){
                    int status=Integer.valueOf(attendanceOvertime.getStatus());
                    switch (status){
                        case 1:
                            attendanceOvertime.setStatus("未确认");
                            break;
                        case 2:
                            attendanceOvertime.setStatus("已确认");
                            break;
                    }
                }
                if(!StringUtils.checkNull(attendanceOvertime.getAllow())){
                    int allow=Integer.valueOf(attendanceOvertime.getAllow());
                    switch (allow){
                        case 0:
                            attendanceOvertime.setAllow("待审批");
                            break;
                        case 1:
                            attendanceOvertime.setAllow("已批准");
                            break;
                        case 2:
                            attendanceOvertime.setAllow("未批准");
                            break;
                    }
                }

                if(attendanceOvertime.getStartTime()!=null &&attendanceOvertime.getEndTime()!=null){

                    Date outTime1=DateFormat.getDate(DateFormat.getDatestr(attendanceOvertime.getStartTime()));
                    Date outTime2=DateFormat.getDate(DateFormat.getDatestr(attendanceOvertime.getEndTime()));
                    long begin=DateFormat.getTime(sdf.format(outTime1));
                    long end=DateFormat.getTime(sdf.format(outTime2));
                    //加班时长
                    attendanceOvertime.setOvertimeHours(DateFormat.returnTime((int)(end-begin)));
                    attendanceOvertime.setStartTime(attendanceOvertime.getStartTime());
                    attendanceOvertime.setEndTime(attendanceOvertime.getEndTime());
                }else {
                    attendanceOvertime.setOvertimeHours("");
                    attendanceOvertime.setStartTime(DateFormat.getDate("0000-00-00"));
                    attendanceOvertime.setEndTime(DateFormat.getDate("0000-00-00"));
                }

                FlowRunPrcs flowRunPrcs= flowRunPrcsMapper.queryByRunId(attendanceOvertime.getRunId());
                if(flowRunPrcs!=null){
                    attendanceOvertime.setFlowPrcs(flowRunPrcs.getFlowPrcs().toString());
                    attendanceOvertime.setPrcsId(flowRunPrcs.getPrcsId().toString());
                }else {
                    attendanceOvertime.setFlowPrcs("");
                    attendanceOvertime.setPrcsId("");
                }
                FlowRun flowRun=flowRunMapper.find(attendanceOvertime.getRunId());
                if(flowRun!=null){
                    attendanceOvertime.setRunId(flowRun.getRunId());
                }

            }

            json.setObj(attendOvertimeList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setTotleNum(pageParams.getTotal());
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("AttendService queryAllAttendOut:"+e);
        }
        return  json;
    }


    /**
     * 加班登记删除操作
     * @param overtimeId
     * @return
     */
    public ToJson deleteAttendanceOvertimeById(Integer overtimeId){
        ToJson tojson = new ToJson();
        try{
            int num = attendanceOvertimeMapper.deleteAttendanceOvertimeById(overtimeId);
            if(num>0){
                tojson.setFlag(0);
                tojson.setMsg("删除成功");
            }
        }catch(Exception e){
            tojson.setFlag(1);
            tojson.setMsg("删除失败");
        }
        return tojson;
    }

    /**
     * 加班登记修改操作
     * @param attendanceOvertime
     * @return
     */
    public ToJson updateAttendanceOvertime(AttendanceOvertime attendanceOvertime){
        ToJson tojson = new ToJson();
        try{
            int num = attendanceOvertimeMapper.updateByExampleSelective(attendanceOvertime);
            if(num>0){
                tojson.setFlag(0);
                tojson.setMsg("修改成功");
            }
        }catch(Exception e){
            tojson.setFlag(1);
            tojson.setMsg("修改失败");
        }
        return tojson;
    }

    /**
     * 查询最近3个月的加班
     * @param userId
     * @return
     */
    public ToJson selectAttendanceOvertimeByUserId(String userId){
        ToJson tojson = new ToJson();
        try{
            List<AttendanceOvertime> attendanceOvertimeList = attendanceOvertimeMapper.selectAttendanceOvertimeByUserId(userId);
            double times = 0.0;//加班总时间
            for (int i = 0; i < attendanceOvertimeList.size(); i++){
                AttendanceOvertime attendanceOvertime = attendanceOvertimeList.get(i);
                if (attendanceOvertime.getOvertimeHours()!=null&&!"".equals(attendanceOvertime.getOvertimeHours())){
                    double time = Double.parseDouble(attendanceOvertime.getOvertimeHours());
                    times = times + time;
                }
            }
            tojson.setFlag(0);
            tojson.setObject(times);
        }catch (Exception e){
            tojson.setFlag(1);
            tojson.setMsg("no");
        }
        return tojson;
    }


}
